# 异步上传图片实现
# 快速上手
demo 地址
https://github.com/poetries/daily-code-practice/tree/master/node/koa/koa2-demo/upload-async
# 源码理解
# demo源码目录
.
├── index.js # 后端启动文件
├── node_modules
├── package.json
├── static # 静态资源目录
│ ├── image # 异步上传图片存储目录
│ └── js
│ └── index.js # 上传图片前端js操作
├── util
│ └── upload.js # 后端处理图片流操作
└── view
└── index.ejs # ejs后端渲染模板
@前端进阶之旅: 代码已经复制到剪贴板
# 后端代码
入口文件 demo/upload-async/index.js
const Koa = require('koa')
const views = require('koa-views')
const path = require('path')
const convert = require('koa-convert')
const static = require('koa-static')
const { uploadFile } = require('./util/upload')
const app = new Koa()
/**
* 使用第三方中间件 start
*/
app.use(views(path.join(__dirname, './view'), {
extension: 'ejs'
}))
// 静态资源目录对于相对入口文件index.js的路径
const staticPath = './static'
// 由于koa-static目前不支持koa2
// 所以只能用koa-convert封装一下
app.use(convert(static(
path.join( __dirname, staticPath)
)))
/**
* 使用第三方中间件 end
*/
app.use( async ( ctx ) => {
if ( ctx.method === 'GET' ) {
let title = 'upload pic async'
await ctx.render('index', {
title,
})
} else if ( ctx.